package wsserver

import (
	"encoding/json"
	"io"
	"sync"
	"time"

	"github.com/gorilla/websocket"
	"inspur.com/cloudware/wscomm"
)

type SafeWriteTunneler interface {
	WriteMessage(message *wscomm.Message) error
	WriteControl(messageType int, data []byte, deadline time.Time) error
	NextReader() (messageType int, r io.Reader, err error)
	io.Closer
}

type DefaultTunnel struct {
	lock *sync.Mutex
	con  *websocket.Conn
}

func (t *DefaultTunnel) WriteControl(messageType int, data []byte, deadline time.Time) (e error) {
	t.lock.Lock()
	e = t.con.WriteControl(messageType, data, deadline)
	t.lock.Unlock()
	return
}

func (t *DefaultTunnel) Close() error {
	return t.con.Close()
}

func (t *DefaultTunnel) NextReader() (messageType int, r io.Reader, err error) {
	return t.con.NextReader()
}

func (t *DefaultTunnel) WriteMessage(m *wscomm.Message) (e error) {
	t.lock.Lock()
	messageByte, _ := json.Marshal(m)
	e = t.con.WriteMessage(websocket.TextMessage, messageByte)
	t.lock.Unlock()
	return
}

func NewDefaultTunnel(con *websocket.Conn) *DefaultTunnel {
	return &DefaultTunnel{
		lock: &sync.Mutex{},
		con:  con,
	}
}
